package com.tarena.lbs.basic.web.repository;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.basic.web.mapper.AdminMapper;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * QueryWrapper是MyBatis-Plus提供的一个查询条件封装类，
 * 用于构建SQL查询条件。它可以通过链式调用方法（如eq、like等）
 * 来设置查询条件，最终生成对应的SQL语句，简化数据库查询操作。
 */
@Repository
public class AdminRepository {
    @Autowired
    private AdminMapper adminMapper;

    /**
     * 根据账号手机号查询记录
     * @param phone
     * @return
     */
    public AdminPO getAdminByPhone(String phone) {
        //select * from lbs_admin where account_phone = #{phone}
        QueryWrapper<AdminPO> query = new QueryWrapper<>();
        query.eq("account_phone", phone);
        return adminMapper.selectOne(query);
    }

    /**
     * 根据id查询记录
     * @param adminId
     * @return
     */
    public AdminPO getAdminById(Integer adminId) {
        return adminMapper.selectById(adminId);

    }

    /**
     * 分页查询
     * @param query
     * @return
     */
    public PageInfo<AdminPO> getAdminByPage(AdminQuery query) {
        QueryWrapper<AdminPO> queryWrapper = assembleAdminQuery(query);//组装查询条件
        PageHelper.startPage(query.getPageNo(), query.getPageSize());//开启分页
        List<AdminPO> pos = adminMapper.selectList(queryWrapper);
        return new PageInfo<>(pos);
    }

    /**
     * 组装查询条件
     * @param query
     * @return
     */
    private QueryWrapper<AdminPO> assembleAdminQuery(AdminQuery query) {
        QueryWrapper<AdminPO> queryWrapper = new QueryWrapper<>();
        //1.accountPhone 账号手机号 相等查询 where account_phone=#{phone}
        if (StringUtils.isNotEmpty(query.getAccountPhone())) {
            queryWrapper.eq("account_phone", query.getAccountPhone());
        }
        //2.nickname 昵称 模糊查询 非空 where nickname like(%#{}%)
        if (StringUtils.isNotEmpty(query.getNickname())) {
            queryWrapper.like("nickname", query.getNickname());
        }
        return queryWrapper;
    }

    /**
     * 根据账号手机号查询记录总数
     * @param accountPhone
     * @return
     */
    public Long countByPhone(String accountPhone) {
        //select count(0) from lbs_admin where accout_phone=#{phone}
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("account_phone",accountPhone);
        return adminMapper.selectCount(queryWrapper);
    }

    /**
     * 保存记录
     * @param poParam
     */
    public void saveAdmin(AdminPO poParam) {
        adminMapper.insert(poParam);
    }
}
